import axios from 'axios';
import { ElMessage,ElLoading } from 'element-plus'
import router from '@/router'

//创建了一个自定义的axios实例对象
const instance = axios.create({
    baseURL:'http://localhost:9999',
    //baseURL: '/api',//基础路径，即路径前缀
    //withCredentials: true //允许向后端发送session凭证
});

let loadingInstance;
// 拦截请求
instance.interceptors.request.use(function (config) {
    // Do something before request is sent
    loadingInstance = ElLoading.service({lock:true,background:'rgba(255,255,255,0)'})

    console.log("config=======",config);

    const token = localStorage.getItem("X-TOKEN");
    // if(token){
    //   //config.headers['Token'] = token;
    //   config.headers.Token = token;
    // }

    token && (config.headers.Token = token);
    

    return config;
  }, function (error) {
    // Do something with request error
    if(loadingInstance){
      loadingInstance.close();
    }
    return Promise.reject(error);
});

// 拦截响应
instance.interceptors.response.use(function (response) {
    //正确响应

    if(loadingInstance){
      loadingInstance.close();
    }

    const result = response.data;

    if(!result.success){

      ElMessage({
        message: result.message,
        type: 'error',
      });

      if(result.code == 520){//未登录
        router.push("/login");       
      }

       
      throw new Error(result.message);
    }

    return result;//即result
  }, function (error) {
    //错误响应
    if(loadingInstance){
      loadingInstance.close();
    }
    console.error(error);
    if (error.response) {//有响应
        // The request was made and the server responded with a status code
        // that falls out of the range of 2xx
        //console.log(error.response.data);
        //console.log(error.response.status);
        //console.log(error.response.headers);
        ElMessage({
            message: "服务端错误，代码："+error.response.status,
            type: 'error',
        });
      } else if (error.request) {//无响应，有请求
        // The request was made but no response was received
        // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
        // http.ClientRequest in node.js
        //console.log(error.request);
        ElMessage({
            message: "无响应！",
            type: 'error',
        });
      } else {//既无响应，也无请求
        // Something happened in setting up the request that triggered an Error
        //console.log('Error', error.message);
        ElMessage({
            message: "前端错误！",
            type: 'error',
        });
      }
      //console.log(error.config);
    return Promise.reject(error);
  });

  export default instance;

  /*
  instance.get('/xxx',{params:{name:'aaa',...}});
  instance.post('/xxx',{name:'aaa'});
  instance.put('/xxx',{name:'aaa'});
  instance.delete('/xxx',{params:{},data:{}});
  */

  export const get = async (url,args)=>{
    return await instance.get(url,{params:args});
  };

  export const post = async (url,args)=>{
    return await instance.post(url,args);
  };

  export const put = async (url,args)=>{
    return await instance.put(url,args);
  };

  export const del = async (url,args)=>{
    return await instance.delete(url,{data:args});
  };